import { NextRequest, NextResponse } from 'next/server'
import { prisma } from '@/lib/db'
import { getUserFromRequest } from '@/lib/auth'

// 暂停任务
export async function POST(
  request: NextRequest,
  { params }: { params: { id: string } }
) {
  try {
    const user = getUserFromRequest(request)
    
    if (!user) {
      return NextResponse.json(
        { error: '未授权访问' },
        { status: 401 }
      )
    }

    const taskId = parseInt(params.id)
    
    if (isNaN(taskId)) {
      return NextResponse.json(
        { error: '无效的任务ID' },
        { status: 400 }
      )
    }

    // 检查任务是否存在
    const task = await prisma.extractionTask.findUnique({
      where: { id: taskId }
    })

    if (!task) {
      return NextResponse.json(
        { error: '任务不存在' },
        { status: 404 }
      )
    }

    // 检查任务状态
    if (task.status !== 'running') {
      return NextResponse.json(
        { error: '只能暂停运行中的任务' },
        { status: 400 }
      )
    }

    // 更新任务状态为暂停
    const updatedTask = await prisma.extractionTask.update({
      where: { id: taskId },
      data: {
        status: 'paused'
      }
    })

    // 更新最新的执行记录
    const latestExecution = await prisma.taskExecution.findFirst({
      where: { 
        taskId: taskId,
        status: 'running'
      },
      orderBy: { createdAt: 'desc' }
    })

    if (latestExecution) {
      await prisma.taskExecution.update({
        where: { id: latestExecution.id },
        data: {
          status: 'paused',
          logs: (latestExecution.logs || '') + '\n任务已暂停。'
        }
      })
    }

    return NextResponse.json({
      message: '任务已暂停',
      task: updatedTask
    })

  } catch (error) {
    console.error('Pause task error:', error)
    return NextResponse.json(
      { error: '暂停任务失败' },
      { status: 500 }
    )
  }
}
